﻿using System;
using System.Collections.Generic;
using System.IO;
using JetBlack.Text;
using JetBlack.IO;

namespace JetBlack.AuthFeedBus.Messages
{
    internal class Entitlements : Message
    {
        public readonly int ClientId;
        public readonly string Feed;
        public readonly string Topic;
        public readonly bool IsFieldLevel;
        public readonly IDictionary<string, object> FieldEntitlements;

        public Entitlements(int clientId, string feed, string topic, bool isFieldLevel, IDictionary<string, object> fieldEntitlements)
            : base(MessageType.Entitlements)
        {
            ClientId = clientId;
            Feed = feed;
            Topic = topic;
            IsFieldLevel = isFieldLevel;
            FieldEntitlements = fieldEntitlements;
        }

        new public static Entitlements Read(Stream reader)
        {
            int clientId = reader.ReadInt32();
            string feed = reader.ReadString();
            string topic = reader.ReadString();
            bool isFieldLevel = reader.ReadBoolean();
            IDictionary<string,object> fieldEntitlements = isFieldLevel ? reader.ReadDictionary() : null;
            return new Entitlements(clientId, feed, topic, isFieldLevel, fieldEntitlements);
        }

        public override Stream Write(Stream writer)
        {
            base.Write(writer);
            writer.Write(ClientId);
            writer.Write(Feed);
            writer.Write(Topic);
            writer.Write(IsFieldLevel);
            if (IsFieldLevel)
                writer.Write(FieldEntitlements);
            return writer;
        }

        override public string ToString()
        {
            return string.Format("{0} {1} {2} {3} {4}", base.ToString(), ClientId, Feed, Topic, IsFieldLevel, IsFieldLevel ? FieldEntitlements.ToDelimitedString() : String.Empty);
        }
    }
}
